<template>
  <div>
    <el-table
      :data="state.tableData"
      class="customer-table"
      max-height="300"
      v-loading="state.loading"
      header-cell-class-name="eltablebg"
      header-row-class-name="radius-8"
      style="width: 100%"
    >
      <el-table-column prop="create_time" :label="$t('stock.stockName')">
        <template #default="r">
          <div class="flex align-center js-st">
            <div>{{ r.row.stock_name }}</div>
            <div>
              <div
                class="share-color text-10 tag us"
                v-if="r.row.stock_type === 1"
              >
                US
              </div>
              <div
                class="share-color text-10 tag hk"
                v-if="r.row.stock_type === 2"
              >
                HK
              </div>
              <div class="mg-lf-base">x{{ r.row.lever_multiple }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stock_code" :label="$t('stock.stockCode')">
      </el-table-column>
      <el-table-column
        prop="lever_type"
        align="center"
        :label="$t('exchange.direction')"
        ><template #default="r">
          <span :class="r.row.lever_type === 1 ? 'text-green' : 'text-red'">
            {{
              r.row.lever_type === 1
                ? $t("exchange.doMore")
                : $t("exchange.short")
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_open_price"
        width="130"
        :label="$t('exchange.openingPrice')"
      >
        <template #default="r">
          {{ $currency(r.row.lever_open_price) }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_hand"
        :label="$t('exchange.lot')"
      >
        <template #default="r">
          {{ $currency(r.row.lever_hand) }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_earnest_money"
        :label="$t('exchange.margin')"
      >
        <template #default="r">
          {{ r.row.lever_earnest_money }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop :label="$t('exchange.stopLoss')">
        <template #default="r">
          <span>{{
            (r.row.stop_win_price ? $currency(r.row.stop_win_price) : "--") +
              "/" +
              (r.row.stop_lose_price ? $currency(r.row.stop_lose_price) : "--")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_overnight_fee"
        :label="$t('exchange.currentPrice')"
      >
        <template #default>{{ $currency(nowPrice) }}</template>
      </el-table-column>
      <el-table-column
        align="center"
        prop
        :label="$t('exchange.profitAndLoss')"
      >
        <template #default="r">
          <span
            :class="
              counprofit(
                r.row.lever_open_price,
                r.row.lever_hand,
                r.row.lever_hand_number,
                r.row.lever_type
              ) < 0
                ? 'text-red'
                : 'text-green'
            "
          >
            {{
              $currency(
                counprofit(
                  r.row.lever_open_price,
                  r.row.lever_hand,
                  r.row.lever_hand_number,
                  r.row.lever_type
                )
              )
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="trade_fee"
        :label="$t('assets.handlingFee')"
      >
        <template #default="r">{{ $currency(r.row.trade_fee) }}</template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="lever_overnight_fee"
        :label="$t('exchange.overnightFee')"
        ><template #default="r">
          <span>{{
            r.row.lever_status === 4
              ? "--"
              : $currency(r.row.lever_overnight_fee)
          }}</span>
        </template></el-table-column
      >
      <el-table-column
        align="center"
        prop="lever_open_time"
        :label="$t('lever.opentime')"
      >
        <template #default="r">
          <span>{{ getTimeZoneDate(r.row.lever_open_time) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="right"
        prop
        :label="$t('assets.operate')"
        label-class-name="right-radius-8"
      >
        <template #default="r">
          <div>
            <el-button type="text" class="free-box" @click="winloseStop(r.row)">
              {{ $t("exchange.stopLoss") }}
            </el-button>
            <el-button type="text" @click="close(r.row.id, r.row)">
              {{ $t("exchange.liquidation") }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <div>
          <Norecord :useDark="true" />
          <!-- <div class="quotet3 text-12 mb-60 l-10">暂无数据</div> -->
        </div>
      </template>
    </el-table>
    <!-- 平仓 -->
    <Messagebox
      :dialog="state.dialog"
      :text="$t('lever.close')"
      :type="3"
      @onconfirm="confirm"
      @oncancer="state.dialog = false"
    />
    <!-- 监听table滚动条触底 -->
    <Tablescroll @scroll="tableScroll" />
  </div>
</template>

<script>
import Norecord from "@/components/noRecord/NoRecord.vue";
import { onMounted, reactive, watch, computed } from "vue";
import {
  stockOrderLeverOrderPage,
  stockOrderLeverClose,
  stockOrderLeverInfo,
} from "@/api/stock-trading";
import {
  demostockOrderLeverClose,
  demostockOrderLeverInfo,
  demostockOrderLeverOrderPage,
} from "@/api/demo";
import UseSystemSetting from "@/commonapi/useSystemSetting";
import Messagebox from "@/components/messageBox/index.vue";
import { ElMessage } from "element-plus";
import Tablescroll from "@/components/tablescroll/index.vue";
import { decimalDigitsInputFilter } from "@/utils/common";
import { useStore } from "vuex";
import { getTimeZoneDate } from "@/utils/times.js";
import { useI18n } from "vue-i18n";

export default {
  name: "Contract",
  components: { Norecord, Messagebox, Tablescroll },
  props: {
    checked: Boolean,
    tradingid: Number,
    nowPrice: Number,
    isRestDate: Boolean,
  },
  emits: ["winlose", "curenttotal"],
  setup(props, { emit }) {
    const $store = useStore();
    const { t } = useI18n();
    const state = reactive({
      listParam: {
        page: 0,
        limit: 10,
        lever_status: 2,
      },
      loading: false,
      tableData: [],
      dialog: false,
      orderId: "", //平仓id
      total: 0,
      closeParam: {},
      leverInfo: {}, //合约下单信息
    });
    /**
     * methods
     */
    // 获取开关状态
    const { virtual_wallet } = UseSystemSetting();
    onMounted(() => {
      if ($store.state.user.token) {
        getList();
      }
    });
    // eslint-disable-next-line no-unused-vars
    watch(
      () => [props.tradingid, $store.state.user.token],
      ([val, oldval], [newtoken, oldtoken]) => {
        console.log(val, oldval, oldtoken);
        if (newtoken == val) {
          state.tableData = [];
          emit("curenttotal", 0);
          return;
        } else {
          if (val !== oldval) {
            state.listParam.page = 0;
            getList();
          }
        }
      }
    );
    watch(
      () => props.checked,
      () => {
        state.listParam.page = 0;
        getList();
      }
    );
    const getorderType = computed(() => {
      return $store.state.exchange.leverOrder_type;
    });
    watch(getorderType, () => {
      state.listParam.page = 0;
      getList();
    });
    const getList = () => {
      const param = { ...state.listParam };
      // 判断是否只显示当前币
      // if (props.checked) {

      // }
      param.stock_id = props.tradingid;
      state.loading = true;
      let setFun = virtual_wallet.value
        ? demostockOrderLeverOrderPage
        : stockOrderLeverOrderPage;
      setFun(param)
        .then((res) => {
          state.loading = false;
          if (state.listParam.page === 0) {
            state.tableData = res.data.items;
            emit("curenttotal", res.data.total);
          } else {
            state.tableData = state.tableData.concat(res.data.items);
          }
          state.total = res.data.total;
        })
        .catch(() => {
          state.loading = false;
        });
    };
    // 止盈止损
    const winloseStop = (item) => {
      emit("winlose", item);
    };
    const gettrading = computed(() => {
      return $store.state.exchange.stock_lever_data;
    });
    // 平仓
    const close = (id, item) => {
      state.orderId = id;
      state.closeParam = item;
      state.dialog = true;
      if (gettrading.value?.id) {
        let setFun = virtual_wallet.value
          ? demostockOrderLeverInfo
          : stockOrderLeverInfo;
        setFun(gettrading.value.id).then((res) => {
          state.leverInfo = res.data;
        });
      }
    };
    // (账户余额+该订单占用保证金+该订单未实现盈亏-该订单隔夜费)/(该订单占用保证金*最低保证金比例)*100% < 100%
    const countIsClose = computed(() => {
      const num1 =
        state.leverInfo?.lever_balance +
        state.closeParam?.lever_earnest_money +
        state.closeParam?.profit -
        state.closeParam?.lever_overnight_fee;
      const num2 =
        (state.closeParam?.lever_earnest_money *
          state.leverInfo?.earnest_money_rate) /
        100;
      console.log(num1, num2, num1 / num2);
      return (num1 / num2) * 100 < 100;
    });
    const confirm = () => {
      if (props.isRestDate) {
        ElMessage.error(t("exchange.unableCloseTip"));
        return false;
      }
      // if (countIsClose.value) {
      //   ElMessage.error("该订单亏损过大，无法单笔平仓");
      //   return false;
      // }
      let setFun = virtual_wallet.value
        ? demostockOrderLeverClose
        : stockOrderLeverClose;
      setFun(state.orderId).then((res) => {
        if (res.code === 200) {
          state.dialog = false;
          ElMessage({
            type: "success",
            message: res.message,
          });
          state.listParam.page = 0;
          getList();
        }
      });
    };
    // table滚动条触底
    const tableScroll = () => {
      if (state.total > state.tableData.length) {
        state.listParam.page = state.listParam.page + 1;
        getList();
      }
    };
    // 计算盈亏
    // 1买多  盈亏 = (当前价-开仓价)*手数*每手个数
    // 2卖空  盈亏 = (开仓价-当前价)*手数*每手个数
    const counprofit = (price, hand, numhand, type) => {
      let profit = 0;
      if (type === 1) {
        profit = (props.nowPrice - price) * hand * numhand;
      } else {
        profit = (price - props.nowPrice) * hand * numhand;
      }
      return decimalDigitsInputFilter(profit, 6);
    };
    const refresh = () => {
      state.tableData = [];
      state.listParam.page = 0;
      state.total = 0;
      getList();
    };
    return {
      state,
      getList,
      winloseStop,
      close,
      confirm,
      tableScroll,
      counprofit,
      getTimeZoneDate,
      gettrading,
      countIsClose,
      refresh,
    };
  },
};
</script>

<style scoped lang="less"></style>
